/** 
 * @Title: Calculate.java 
 * @Package wordrelationship.imp 
 * @Description: TODO
 * @author HeYan
 * @date 2016年10月19日 上午10:57:25 
 */
package wordrelationship.imp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.zizo.util.ConnectionPool;

/**
 * @ClassName: Calculate
 * @Description: TODO
 * @author HeYan
 * @date 2016年10月19日 上午10:57:25
 * 
 */
public class Calculate implements Runnable {
	private Connection conn;
	private Map<Word, Double> map;
	private String tablename;

	public Calculate(String tablename) {
		this.conn = ConnectionPool.getConnection("word2vec", "localhost");
		this.map = new HashMap<Word, Double>();
		this.tablename = tablename;
	}

	public final void getWord() {
		Statement st = null;
		ResultSet rs = null;
		String sql = "SELECT word1,word2,p FROM relationship_" + tablename;
		try {
			st = conn.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				String word1 = rs.getString(1);
				String word2 = rs.getString(2);
				double p = rs.getDouble(3);
				Word word = new Word(word1, word2);
				if (map.keySet().contains(word)) {
					map.put(word, map.get(word) + p);
				} else {
					map.put(word, p);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public final void doMap() {
		for (Map.Entry<Word, Double> entry : map.entrySet()) {
			Word word = entry.getKey();
			double p = entry.getValue();
			insertData(word.getWord1(), word.getWord2(), p);
		}
	}

	public void createTable() {
		String sql = "CREATE TABLE final_" + tablename + " like relationship";
		Statement st = null;
		try {
			st = conn.createStatement();
			st.executeUpdate(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public final void insertData(String word1, String word2, double p) {
		PreparedStatement ps = null;
		String sql = "INSERT INTO final_" + tablename + "(word1,word2,p) values(?,?,?)";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, word1);
			ps.setString(2, word2);
			ps.setDouble(3, p);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		createTable();
		getWord();
		doMap();
	}

	public static void main(String[] args) {
		ExecutorService fix = Executors.newFixedThreadPool(20);
		String tablename = "3800";
		fix.execute(new Calculate(tablename));
		fix.shutdown();
	}
}
